<template>
	
	<view class="container">
		<!-- 头部搜索区 -->
		<view class="header">
			<text class="iconfont icon-soushuo"></text>
			<input type="text" :value="searchContent" :placeholder="hotKeyword"
			 placeholder-class="placeholder" @input="handleChange" 
			 @confirm="confirmSearch"/>
			<text class="clear" @tap="clearSearchContent" v-show="searchContent.length">x</text>
		</view>
		
		
		<block v-if="!searchResultSongs.length">
			<!-- 搜索内容 -->
			<view class="searchRecords" v-if="searchContent.length" v-show="display">
				<view class="searchContent">搜索内容：{{searchContent}}</view>
				<view class="searchList">
					<view class="searchItem" @tap="btnSearchSongList(item.name)" v-for="item in searchSongInfo" :key="item.id">
						<text class="iconfont icon-soushuo"></text>
						<text class="content">{{item.name}}</text>
					</view>
				</view>
			</view>
			
			<block v-else>
				<!-- 搜索历史记录 -->
				<view class="history" v-if="historyList.length">
					<view class="title">历史</view>
					<scroll-view scroll-x class="scrollHistory">
						<view @tap="btnSearchHistory(item)" class="historyItem" v-for="(item,index) in historyList" :key="index">
							{{item}}
						</view>
					</scroll-view>
					<!-- 删除 -->
					<text class="iconfont icon-shanchu1 delete" @tap="deleteSearchHistory"></text>
				</view>
				<!-- 热搜榜 -->
				<view class="hot">
					<view class="title">热搜榜</view>
					<!-- 热搜列表 -->
					<view class="hotList">
						<view class="hotItem" v-for="(item,index) in hotSongList"
						 :key="index" @tap="toHotListItem(item.searchWord)">
							<text class="order">{{index + 1}}.</text>
							<text class="songName">{{item.searchWord}}</text>
							<image v-if="item.iconUrl" :src="item.iconUrl"></image>
							<!-- <text class="content">aaa</text> -->
						</view>
					</view>
				</view>
			</block>
		</block>
				
		<block v-else>
			<!-- 确认搜索歌曲返回数据的页面 -->
			<view class="searchSongResult">
				<!-- 标题 -->
				<view class="songTitle">
					<view class="songItem" @tap="switchNav" data-id="1">
						<text :class="songType ==1 ? 'activeColor' : ''">单曲</text>
					</view>
					<view class="songItem" @tap="switchNav" data-id="2">
						<text :class="songType ==1000 ? 'activeColor' : ''">歌单</text>
					</view>
					<view class="songItem" @tap="switchNav" data-id="3">
						<text :class="songType ==1014 ? 'activeColor' : ''">视频</text>
					</view>
				</view>
				<!-- <loadTip v-else></loadTip> -->
				<!-- 单曲歌曲页面 -->
				<scroll-view scroll-y class="oneSongScroll" v-if="switchType == 1">
					<view class="oneSongItem" v-for="(item,index) in searchResultSongs" :key="item.id"
					>
						<view class="songs" @tap="btnSongDetail(item.id,index)">
							<text class="songName">{{item.name}}</text>
							<view class="songInfo">
								<text class="author">{{item.artists[0].name}}</text>
								<view class="fenge">-</view>
								<text class="describe">{{item.album.name}}</text>
							</view>
						</view>
						<text class="iconfont icon-mv" v-if="item.mvid" @tap="toVideoDetail(item.mvid,'0')"></text>
					</view>	
				</scroll-view>
				<!-- 歌单页面 -->
				<scroll-view class="songSheetScroll" scroll-y  v-else-if="switchType == 2">
					<view class="scrollItem" v-for="(item,index) in searchResultSongs" :key="item.id"
					@tap="toSongSheetDetail(item.id)">
						<image :src="item.coverImgUrl"></image>
						<view class="songSheetInfo">
							<text class="songSheetName">{{item.name}}</text>
							<text class="author">
								{{item.trackCount}}首,by {{item.creator.nickname}},播放{{item.playCount>=10000?parseInt(item.playCount/10000)+'万':item.playCount}}次
							</text>
						</view>
					</view>
				</scroll-view>	
				<!-- 视频页面 -->
				<scroll-view v-else scroll-y class="videoScroll">
					<view class="videoItem" v-for="(item,index) in searchResultSongs" :key="item.vid"
					@tap="toVideoDetail(item.vid,item.type)">
					    <view class="videoTitle">
					        {{item.title}}{{item.type==0?' - '+item.creator[0].userName:''}}
					    </view>    
					    <image class="videoImg" :src="item.coverUrl"></image>
					</view>
				</scroll-view>	
			</view>
		</block>	
	</view>
</template>


<script>
	let timer = null
	import loadTip from '../../components/loadTip/loadTip.vue'
	export default {
		data() {
			return {
				hotKeyword:'', // 热歌词
				hotSongList:[], // 热歌榜数据
				searchContent:'', // 用户搜索的内容
				searchSongInfo:[], // 搜索到的歌曲数据
				historyList:[], // 用户搜索过的记录存放
				pageNum:0,
				searchResultSongs:[], // 搜索返回到的相关歌曲数据
				display:true, // 控制搜索内容显示隐藏
				index:0, // 切换歌曲的下标
				switchType:1, // 切换单曲 歌单 视频的标识
				songType:1, // 1时搜索到的是单曲 1000是歌单 1014是视频
				activeSong:'red',// 点击谁 谁切换颜色
				isShow:0,
			}	
		},
		components:{loadTip},
		onLoad() {
			this.getHotKeyword()
			this.getHotSongList()
			
			this.getUserSearchHistory()
			// if(this.searchContent == '') {
			// 	this.searchResultSongs = []
			// }
			// 获取App.vue全局实例
			const appData = getApp()
			this.appData = appData
			// this.appData.methods.getswitchSongs(this.searchResultSongs)
			// console.log(this.appData.methods);
			// this.$switchSong(this.searchResultSongs,this.index)
			
			// 订阅方,来自songDetail传过来的参数type
			uni.$on('switchType',(type) => {
				console.log(type,'我要切歌了');
				if(type === 'pre'){ // 切换上一首
				// if(this.index === 0){this.index = this.recommendList.length}
				// 等同于上面,如果是第一首歌切换上一首 就是播放最后一首 length-1 就是数组最后一个
					(this.index === 0) && (this.index = this.searchResultSongs.length)
					this.index -= 1
				}else {// 切换下一首
					if(this.index === this.searchResultSongs.length - 1) {this.index = -1}
					// (this.index === this.recommendList.length - 1) && (this.index = -1)
					this.index += 1
				}
				let musicId = this.searchResultSongs[this.index].id
				// 将musicId 回传给songDetail页面
				uni.$emit('musicId',musicId)
				console.log(musicId,'recommendSong');
			})
		},
		methods: {
			// 读取本地用户搜索记录
			getUserSearchHistory() {
				let userSearchHistory = uni.getStorageSync("userSerachHistory")
				if(userSearchHistory){
					this.historyList = userSearchHistory
				}
			},
			// 获取热歌词
			async getHotKeyword() {
				const res = await this.$myRequest('/search/default')
				this.hotKeyword = res.data.showKeyword
			},
			async getHotSongList() { // 获取热歌榜
				const res = await this.$myRequest('/search/hot/detail')
				console.log(res);
				this.hotSongList = res.data
			},
			// 搜索框发生改变
			// input 和 change的区别是 input实时改变 change是焦点失去
			handleChange(event) {
				this.display = true // 只要有数据 就隐藏掉搜索内容标签
				this.searchContent = event.detail.value.trim() // 获取输入的值
				// 搜索性能优化：函数防抖  500ms才发起请求
				// 频繁操作,只要最后一次的操作,在300ms内输入不请求
				if(timer !== null){
					clearTimeout(timer)
				}
				timer = setTimeout(() => {
					this.getSearchSongInfo()
				},300)
			},
			// 关键字搜索到的模糊信息
			async getSearchSongInfo() {
				if(!this.searchContent){ // 为空就不发请求
					return
				}
				// 获取模糊搜索到的歌曲 匹配数据
				const res = await this.$myRequest('/search',{
					keywords: this.searchContent,
					limit: 10
				})
				this.searchSongInfo = res.result.songs
				
			},
			// 回车发起搜索请求
			confirmSearch(e){
				this.display = false 
				let content = e.detail.value
				console.log(content);
				this.pushSearchHistory(this.searchContent)
				this.getSearch(content,this.songType)
			},
			// 点击热搜榜歌曲搜索
			toHotListItem(songName) {
				this.display = false
				this.pushSearchHistory(songName)
				this.getSearch(songName,this.songType)
			},
			btnSearchHistory(songName){ // 点击搜索历史记录歌曲搜索
				this.display = false
				this.pushSearchHistory(songName)
				this.getSearch(songName,this.songType)
			},
			btnSearchSongList(songName){ // 点击关键字歌曲列表搜索
				this.display = false
				this.pushSearchHistory(songName)
				this.getSearch(songName,this.songType)
			},
			
			// 点击歌曲 跳转至播放页面
			btnSongDetail(songId,index){
				this.index = index
				uni.navigateTo({
					url:'/pages/songDetail/songDetail?songId=' + songId
				})
			},
			// 点击歌单跳转到歌单详情页
			toSongSheetDetail(songSheetId){
				uni.navigateTo({
					url:'/pages/songSheetDetail/songSheetDetail?songSheetId=' + songSheetId
				})
			},
			// 点击视频 跳转到视频播放页面
			toVideoDetail(videoId,videoType){
				console.log(videoId);
				console.log(videoType);
				// videoType = 0 是MV =1 是视频
				uni.navigateTo({
					url:'/pages/videoDetail/videoDetail?videoId=' + videoId + '&videoType=' + videoType
				})
			},
			
			
			
			// 点击搜索到的标题 切换样式
			switchNav(e) {
				let id = e.currentTarget.dataset.id
				console.log(id);
				if(id == 1){ // 如果等1 
					this.switchType = id
					this.songType = 1
				}else if(id == 2){
					this.switchType = id
					this.songType = 1000
				}else{
					this.switchType = id
					this.songType = 1014
				}
				this.getSearch(this.searchContent,this.songType)
				console.log(this.songType);
			},
			
			
			
			
			
			// 将搜索的函数进行封装
			async getSearch(content,songType) {
				this.searchResultSongs = [] // 先清空数组
			    // 保存查询内容
			    this.searchContent = content;
			    // 对查询类型进行判断
			    // 当songType为 1是单曲   为 1000是歌单   为 1014是视频
			    // let songType = 1;
			    let searchResultData = await this.$myRequest('/search', { keywords: content, limit: 20, offset: this.pageNum * 20, type:songType })
			    console.log(searchResultData);
				if(this.songType == 1){
					
					this.searchResultSongs = searchResultData.result.songs
				}else if(this.songType == 1000){this.searchResultSongs = searchResultData.result.playlists }else {
					this.searchResultSongs = searchResultData.result.videos
				}
				
			  },
			// 封装添加历史记录
			pushSearchHistory(searchContent){
				// 检测它的下标是否不等于-1 证明有已加入的关键字 先删除
				if(this.historyList.indexOf(searchContent) !== -1) {
					// splice() 移除对应的关键字
					this.historyList.splice(this.historyList.indexOf(searchContent),1)
				}
				// 再将用户搜索的关键字添加到搜索记录里
				// unshift() 方法 添加进去， 而且新添加的都排在前面
				this.historyList.unshift(searchContent)
				// 用以用户下次刷新 继续保存
				uni.setStorageSync("userSerachHistory",this.historyList)
			},
			// 删除用户搜索历史记录
			deleteSearchHistory(){
				uni.showModal({
				    content: '确定清空全部历史记录？',
					confirmText:'清空',
					confirmColor:'#0099ff',
					cancelColor:'#0099ff',
				    success: (res) => {
				        if (res.confirm) {
				            this.historyList = []
				            uni.removeStorageSync("userSerachHistory")
				        }
				    }
				});
				
			},
			// 清空用户正在搜索的关键字
			clearSearchContent() {
				this.searchContent = ''
				this.searchSongInfo = []
				this.searchResultSongs = []
				
			}
		}
	}
</script>

<style lang="scss">
.container {
	padding: 0 20rpx;
	// 头部搜索样式
	.header {
		display: flex;
		position: relative;
		height: 80rpx;
		line-height: 80rpx;
		padding: 10rpx 0;
		.icon-soushuo {
			position: absolute;
			left: 15rpx;
			font-size: 50rpx;
			color: #ccc;
		}
		input {
			flex: 1;
			background-color: #f6f6f6;
			// border-bottom: 1rpx solid #f6f6f6;
			border-radius: 40rpx;
			font-size: 36rpx;
			height: 80rpx;
			// text-align: center;
			padding-left: 80rpx;
		}
		.placeholder {
			color: #bbb;
		}
		.clear {
			position: absolute;
			top: 10rpx;
			right: 15rpx;
			width: 10vw;
			height: 50rpx;
			text-align: center;
			font-size: 65rpx;
			line-height: 50rpx;
			color: #bbb;
			padding: 10rpx;
			z-index: 1000;
		}
	}
	// 搜索记录样式
	.searchRecords {
		.searchContent {
			color: $cloundMusic-color;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 34rpx;
			border-bottom: 1rpx solid $cloundMusic-color;
		}
		.searchList {
			
			.searchItem {
				height: 80rpx;
				line-height: 80rpx;
				display: flex;
				.content {
					flex: 1;
					margin-left: 20rpx;
					border-bottom: 1rpx solid #eee;
					font-size: 30rpx;
				}
			}
		}
	}
	// 历史记录
	.history {
		display: flex;
		flex-wrap: wrap; // 流式布局
		line-height: 50rpx;
		
		.title {
			font-size: 36rpx;
			height: 50rpx;
			width: 80rpx;
			color: #000;
			padding: 10rpx 0;
			text-align: center;
		}
		.scrollHistory {
			flex: 1;
			white-space: nowrap;
			overflow: hidden;
			.historyItem {
				display: inline-block;
				background-color: #f3f3f3;
				border-radius: 32rpx;
				padding: 10rpx 30rpx;
				margin: 0 15rpx;
				font-size: 30rpx;
			}
		}
		.icon-shanchu1 {
			width: 50rpx;
			height: 50rpx;
			padding: 10rpx 30rpx;
			text-align: center;
			font-size: 40rpx;
		}
		.delete {
			
		}
	}
	// 热搜样式
	.hot {
		
		.title {
			font-size: 34rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 1rpx solid #eee;
		}
		.hotList {
			display: flex;
			flex-wrap: wrap; // 换行
			// flex-direction: column;	// 改变flex布局 纵向排列
			.hotItem {
				width: 50%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 26rpx;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				
				.order {
					margin: 0 10rpx;
				}
				.songName {
					
				}
				image {
					width: 35rpx;
					height: 20rpx;
					margin-left: 10rpx;
				}
				.content {
					width: 50%;
				}
			}
		}
	}
	// 搜索返回歌曲样式
	.searchSongResult {
		
		.songTitle {
			// background-color: $cloundMusic-color;
			display: flex;
			width: 100%;
			height: 70rpx;
			line-height: 70rpx;
			
			.songItem {
				text-align: center;
				width: 33.3%;
				font-size: 28rpx;
				border-bottom: 3rpx solid #007AFF;
				.activeColor {
					border-bottom: 5rpx solid #000;
				}
			}
		}
		// 单曲样式
		.oneSongScroll {
			/* #ifdef MP-WEIXIN */
			height: calc(100vh - 170rpx); //140rpx 头部和导航的高度总和
			/* #endif */
			/* #ifdef H5 */
			height: calc(100vh - 250rpx);
			/* #endif */
			.oneSongItem {
				display: flex;
				// 改变flex布局 纵向排列
				flex-direction: column;
				margin: 20rpx;
				font-size: 20rpx;
				.songs{
					.songName {
						font-size: 30rpx;
						max-width: 200rpx; // 允许最宽400rpx
						white-space: nowrap; // 不允许换行
						font-weight: bolder;
						color: $cloundMusic-color;
					}
					.songInfo {
						display: flex;
						.fenge {
							margin: 0 10rpx;
						}
						text {
							//	有些歌名会太长 所以修饰一下
							max-width: 400rpx; // 允许最宽400rpx
							white-space: nowrap; // 不允许换行
							// overflow: hidden; // 超出的部分隐藏
							// text-overflow: ellipsis; //超出的部分用省略号代替
						}
					}
				}
				.iconfont {
					position: absolute;
					right: 0;
					width: 80rpx;
					height: 70rpx;
					line-height: 70rpx;
					font-size: 50rpx;
					text-align: center;
					z-index: 99;
				}	
			}
		}
		// 歌单样式
		.songSheetScroll {
			/* #ifdef MP-WEIXIN */
			height: calc(100vh - 170rpx); //140rpx 头部和导航的高度总和
			/* #endif */
			/* #ifdef H5 */
			height: calc(100vh - 250rpx);
			/* #endif */
			.scrollItem {
				position: relative;
				// 纵向排列
				display: flex;
				margin: 20rpx 0 0 20rpx;
				image {
					width: 100rpx;
					height: 100rpx;
					border-radius: 8rpx;
				}
				.songSheetInfo {
					display: flex;
					// 改变flex布局 纵向排列
					flex-direction: column;
					margin-left: 20rpx;
					
					text {
						height: 50rpx;
						line-height: 50rpx;
						font-size: 24rpx;
						white-space: nowrap; // 不允许换行
						
					}
				}
			}
		}
		// 视频滚动样式
		.videoScroll{
			/* #ifdef MP-WEIXIN */
			height: calc(100vh - 170rpx); //140rpx 头部和导航的高度总和
			/* #endif */
			/* #ifdef H5 */
			height: calc(100vh - 250rpx);
			/* #endif */
			.videoItem {
				margin-top: 10rpx;
				padding: 0 %3;
				.videoTitle {
					margin-bottom: 5rpx;
					font-size: 26rpx;
					max-width: 500rpx; // 允许最宽400rpx
					white-space: nowrap; // 不允许换行
					overflow: hidden; // 超出的部分隐藏
					text-overflow: ellipsis; 
					padding-bottom: 10rpx;
				}
				.videoImg {
					border-radius: 10rpx;
					width: 100%;
				}
			}
		}
	}
}
</style>
